package com.waimai.mobile.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.waimai.mobile.R;
import com.waimai.mobile.api.WaiMaiServer;
import com.waimai.mobile.api.entity.Order;
import com.waimai.mobile.api.entity.ReceiveAddress;
import com.waimai.mobile.api.entity.Restaurant;
import com.waimai.mobile.api.model.ResponseModel;
import com.waimai.mobile.misc.Util;
import com.waimai.mobile.ui.WaiMaiApp;
import com.waimai.mobile.ui.adapter.OrderFoodItemAdapter;
import com.waimai.mobile.ui.fragment.RestaurantOrderFragment;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

/**
 * Created by lin on 2015/6/20.
 */
@EActivity(R.layout.activity_order_confirm)
public class OrderConfirmActivity extends BaseActivity02{

    private AlertDialog dialog;

    @Extra("order")
    public Order order;

    @App
    public WaiMaiApp app;

    @RestService
    public WaiMaiServer server;

    @Bean
    public OrderFoodItemAdapter adapter;

    @ViewById
    public LinearLayout chooseAddresssContainerLL;

    @ViewById
    public LinearLayout addressContainerLL;


    @ViewById
    public TextView userNameAndPhoneTv;

    @ViewById
    public TextView addressNameTv;


    @ViewById
    public EditText remarkEdt;

    @ViewById
    public TextView deliveryPriceTv;

    @ViewById
    public TextView restaurantNameTv;

    @ViewById
    public ListView orderFoodLv;

    @ViewById
    public TextView totalPriceTv;

    @ViewById
    public Button submitOrderBtn;


    @AfterInject
    public void afterInject(){
        server.setHeader("Content-Type", "application/json");
    }

    @AfterViews
    public void afterViews(){
        setActionBarTitle("确认订单");
        dialog = new AlertDialog.Builder(this)
                .setMessage("正在加载数据..")
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        finish();
                    }
                })
                .create();
        dialog.show();
        checkOrder(order);
    }

    @Click(R.id.chooseAddresssContainerLL)
    public void chooseAddresssContainerLLClick(){
        if(app.getUser() == null){
            Intent intent = new Intent(this, LoginActivity_.class);
            startActivity(intent);
        }else{
            Intent intent = new Intent(this, AddressListActivity_.class);
            intent.putExtra(AddressListActivity.EXTRA_CHOOSE, true);
            startActivityForResult(intent, AddressListActivity.REQUEST_GET_ADDRESS);
        }
    }

    @Click(R.id.addressContainerLL)
    public void addressContainerLLClick(){
        Intent intent = new Intent(this, AddressListActivity_.class);
        intent.putExtra(AddressListActivity.EXTRA_CHOOSE, true);
        intent.putExtra(AddressListActivity.EXTRA_ADDRESS_ID, order.getReceiveaddress().getAddressId());
        startActivityForResult(intent, AddressListActivity.REQUEST_GET_ADDRESS);
    }

    @Click(R.id.submitOrderBtn)
    public void submitOrderBtnClick(){
        if(order.getReceiveaddress() == null){
            Toast.makeText(this, "请选择收餐地址", Toast.LENGTH_SHORT).show();
        }else if(app.getUser() == null){
            Intent intent = new Intent(this, LoginActivity_.class);
            startActivity(intent);
        }else{
            String remark = remarkEdt.getText().toString().trim();
            if(remark != null && !"".equals(remark)){
                order.setRemark(remark);
            }

            dialog.setMessage("正在下单...");
            dialog.show();
            submitOrder(order);
        }
    }

    public void initViews(){
        if(order.getReceiveaddress() == null){
            chooseAddresssContainerLL.setVisibility(View.VISIBLE);
            addressContainerLL.setVisibility(View.GONE);
        }else{
            chooseAddresssContainerLL.setVisibility(View.GONE);
            addressContainerLL.setVisibility(View.VISIBLE);
        }
        deliveryPriceTv.setText(order.getDeliveryPrice() +"");
        restaurantNameTv.setText(order.getRestaurant().getRestaurantName());
        order.setTotalPrice(order.getTotalPrice() + order.getDeliveryPrice());
        totalPriceTv.setText(order.getTotalPrice() + "");
    }

    @Background(id="checkRestaurant")
    public void checkOrder(Order order){
        try{
            ResponseModel<Restaurant> model = server.checkRestaurant(order.getRestaurant().getRestaurantId(), order.getRestaurant());
            if(model != null){
                switch (model.getStatus().getStatusCode()){
                    case ResponseModel.STATUS_CHECK_PASSED:
                        checkPassed();
                        break;

                    case ResponseModel.STATUS_CHECK_NOT_EXTIST:
                        checkNotExist();
                        break;

                    case ResponseModel.STATUS_CHECK_NOT_PASSED:
                        checkNotPassed();
                        break;
                }
            }else{

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Background
    public void submitOrder(Order order){
        try{
            ResponseModel<Order> model = server.submitOrder(order.getRestaurant().getRestaurantId(), order);
            if(model != null){
                switch (model.getStatus().getStatusCode()){
                    case ResponseModel.STATUS_CHECK_PASSED:
                        checkPassed();
                        break;
                    case ResponseModel.STATUS_CHECK_NOT_EXTIST:
                        checkNotExist();
                        break;
                    case ResponseModel.STATUS_REQUEST_SUCCESS:
                        submitSuccess(model.getData());
                        break;
                    case ResponseModel.STATUS_REQUEST_FAILED:
                        submitFailed();
                        break;
                }
            }else{
                serverError();
            }
        }catch (Exception e){
            e.printStackTrace();
            netError();
        }
    }


    @UiThread
    public void checkPassed(){
        dialog.dismiss();
        adapter.setOrderFoods(order.getOrderfoods());
        orderFoodLv.setAdapter(adapter);
        Util.setListViewHeightBasedOnChildren(orderFoodLv);
        initViews();
    }

    @UiThread
    public void checkNotExist(){
        Toast.makeText(this, "餐厅不存在", Toast.LENGTH_SHORT).show();
        setResult(RestaurantOrderFragment.RESULT_RESTAURANT_NOT_EXTIST);
        dialog.cancel();
    }

    @UiThread
    public void checkNotPassed(){
        Toast.makeText(this, "餐厅信息有变化，请重新确认", Toast.LENGTH_LONG).show();
        setResult(RestaurantOrderFragment.RESULT_RESTAURANT_CHANGED);
        dialog.cancel();
    }

    @UiThread
    public void submitSuccess(Order order){
        Toast.makeText(this, "下单成功", Toast.LENGTH_SHORT).show();
        dialog.dismiss();
        Intent intent = new Intent(this, OrderDetailActivity_.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("order", order);
        startActivity(intent);
        finish();
    }

    @UiThread
    public void submitFailed(){
        Toast.makeText(this, "下单失败，请稍后重试", Toast.LENGTH_SHORT).show();
        dialog.dismiss();
    }

    @UiThread
    public void serverError(){
        Toast.makeText(this, "服务器错误", Toast.LENGTH_LONG).show();
        dialog.cancel();
    }

    @UiThread
    public void netError(){
        Toast.makeText(getApplicationContext(), "网络错误", Toast.LENGTH_SHORT).show();
        dialog.cancel();
    }

    @OnActivityResult(AddressListActivity.REQUEST_GET_ADDRESS)
    public void onResult(int resultCode, Intent data){
        switch (resultCode){
            case AddressListActivity.RESULT_GET_SUCCESS:
                ReceiveAddress address = (ReceiveAddress) data.getSerializableExtra(AddressListActivity.EXTRA_DATA);
                getAddressSuccess(address);
                break;

            case AddressListActivity.RESULT_GET_FAILED:
                getAddressFailed();
                break;
        }
    }

    public void getAddressSuccess(ReceiveAddress address){
        order.setReceiveaddress(address);

        chooseAddresssContainerLL.setVisibility(View.GONE);
        addressContainerLL.setVisibility(View.VISIBLE);
        if(address.getUserName() == null){
            userNameAndPhoneTv.setText(address.getPhone());
        }else{
            userNameAndPhoneTv.setText(address.getUserName()+"  "+address.getPhone());
        }
        addressNameTv.setText(address.getAddressName());
    }

    public void getAddressFailed(){
        Toast.makeText(this, "选择地址失败,请重试", Toast.LENGTH_SHORT).show();
        chooseAddresssContainerLL.setVisibility(View.VISIBLE);
        addressContainerLL.setVisibility(View.GONE);
    }
}
